package com.scs.application.modules.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.core.utils.UtilNum;
import com.scs.application.modules.device.entity.*;
import com.scs.application.modules.device.enums.CheckResult;
import com.scs.application.modules.device.enums.CheckType;
import com.scs.application.modules.device.enums.DeviceBusMap;
import com.scs.application.modules.device.enums.DeviceStatus;
import com.scs.application.modules.device.mapper.DeviceWorkMapper;
import com.scs.application.modules.device.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 *  设备工作表 服务实现类
 */
@Service
public class DeviceWorkServiceImpl extends BaseServiceImpl<DeviceWorkMapper, DeviceWork> implements DeviceWorkService {
    @Lazy
    @Autowired
    private DeviceWorkItemService deviceWorkItemService;
    @Lazy
    @Autowired
    private DeviceLedgerService deviceLedgerService;
    @Lazy
    @Autowired
    private DeviceContractPayableService deviceContractPayableService;
    @Lazy
    @Autowired
    private DeviceWorkOfferService deviceWorkOfferService;

    @Override
    public boolean saveOrUpdate(DeviceWork entity) {
        if (entity.isNewRecord()) {
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(DeviceBusMap.getSerialKey(entity.getBusType())));
        }
        boolean isNew = entity.isNewRecord();
        super.saveOrUpdate(entity);

        if (isNew ) {
            // 采购报价保存后，根据所选择的采购单添加相关报价明细
            if (entity.getBusType().equals(DeviceBusMap.DEVICE_PO_OFFER)) {
                this._addOfferDtlByPo(entity);
            }

            // 采购合同保存后，根据所选择的采购单添加相关合同明细
            if (entity.getBusType().equals(DeviceBusMap.DEVICE_PO_CONTRACT)) {
                this._addContractDtlByOffer(entity);
            }

            // 安装验收保存后，根据所选择的采购单添加相关 明细
            if (entity.getBusType().equals(DeviceBusMap.DEVICE_PO_ACCEPT)) {
                this._addAcceptDtl(entity);
            }

            // 入库保存后，添加入库明细
            if (entity.getBusType().equals(DeviceBusMap.DEVICE_PO_WI)) {
                this._addWiDtl(entity);
            }
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<String> childIdList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().in("work_id", idList)).stream().map(DeviceWorkItem::getId).collect(Collectors.toList());
        if (ObjectUtil.length(childIdList) > 0) {
            deviceWorkItemService.removeCascadeByIds(childIdList);
        }

        deviceContractPayableService.remove(Wrappers.<DeviceContractPayable>query().in("work_id", idList));

        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void beforeHandleFlowChange(FlowContext flowContext, DeviceWork newEntity) {
        //5 维修前置逻辑
        _beforeRepair(newEntity,flowContext);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afterHandleFlowChange(FlowContext flowContext, DeviceWork newEntity) {
        List<DeviceWorkItem> childList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().eq("work_id", newEntity.getId()));

        //5 盘点后续逻辑
        _afterCheck(newEntity,childList,flowContext);

        //5 折旧后续逻辑
        _afterOld(newEntity,childList,flowContext);

        if (!flowContext.isEndNode()) {
            return;
        }
        BusinessException.throwErrorIf(ObjectUtil.length(childList) == 0, "业务明细为空，无法审核通过");

        // 处理台账信息
        deviceLedgerService.transferByDeviceWork(childList, newEntity,flowContext.getButton());

        //1 采购单审核通过后续逻辑
        _afterPo(newEntity,childList);

        //2 采购论证审核通过后续逻辑
        _afterPoArgument(newEntity,childList);

        //3 采购报价审核通过后续逻辑
        _afterPoOffer(newEntity,childList);

        //4 采购合同审核通过后续逻辑
        _afterPoContract(newEntity,childList);

        //4 安装验收审核通过后续逻辑
        _afterPoAccept(newEntity,childList);

        //4 采购入库审核通过后续逻辑
        _afterPoWi(newEntity,childList);

        //4 调价审核通过后续逻辑
        _afterPriceChange(newEntity,childList, true);

    }

    /***
     * @param
     * @Description:  采购单审核通过后续逻辑
     */
    private void _afterPo(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PO)) {
            return;
        }
        List<DeviceWorkItem> childListNeed = childList.stream().filter(tmp -> tmp.getFlagArgument() == GlobalConsts.YES).collect(Collectors.toList());
        if (ObjectUtil.length(childListNeed) == 0) {
            return;
        }

        //生成论证单
        DeviceWork deviceWork = new DeviceWork();
        BeanUtil.copyProperties(work,deviceWork);
        deviceWork.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        deviceWork.setFlowModifier(null).setFlowModified(null).setFlowStatus(GlobalConsts.FLOW_START_VALUE);
        deviceWork.setBusType(DeviceBusMap.DEVICE_ARGUMENT);
        deviceWork.setRemark(StrUtil.format("采购单: {}",work.getBusKey()));
        this.saveOrUpdate(deviceWork);

        for(DeviceWorkItem item : childListNeed) {
            item.setWorkId(deviceWork.getId()).setWorkItemId(item.getId());
            item.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        }
        deviceWorkItemService.saveOrUpdateBatch(childListNeed);
    }

    /***
     * @param
     * @Description:  采购论证审核通过后续逻辑
     */
    private void _afterPoArgument(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_ARGUMENT)) {
            return;
        }
        List<String> itemIdListPass = childList.stream().filter(tmp -> tmp.getFlagArgumentPass() == GlobalConsts.YES).map(DeviceWorkItem::getWorkItemId).collect(Collectors.toList());
        List<String> itemIdListNoPass = childList.stream().filter(tmp -> tmp.getFlagArgumentPass() != GlobalConsts.YES).map(DeviceWorkItem::getWorkItemId).collect(Collectors.toList());
        if (ObjectUtil.length(itemIdListPass) > 0) {
            deviceWorkItemService.update(Wrappers.<DeviceWorkItem>update().set("flag_argument_pass",GlobalConsts.YES_STR).in("id",itemIdListPass ));
        }
        if (ObjectUtil.length(itemIdListNoPass) > 0) {
            deviceWorkItemService.update(Wrappers.<DeviceWorkItem>update().set("flag_argument_pass",GlobalConsts.NO_STR).in("id",itemIdListNoPass ));
        }
    }

    /***
     * @param
     * @Description:  采购报价审核通过后续逻辑
     */
    private void _afterPoOffer(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PO_OFFER)) {
            return;
        }

//        childList.stream().filter(item -> StringUtils.isBlank(item.getSupplierName())).findFirst().ifPresent(find -> {
//            BusinessException.throwError("设备[%s]未指定供应商,请检查",find.getDeviceName());
//        });
//
//        childList.stream().filter(item -> StringUtils.isBlank(item.getMfgName())).findFirst().ifPresent(find -> {
//            BusinessException.throwError("设备[%s]未指定厂商,请检查",find.getDeviceName());
//        });
//
//        childList.stream().filter(item -> item.getDevicePrice() == null || item.getDevicePrice() <=0).findFirst().ifPresent(find -> {
//            BusinessException.throwError("设备[%s]价格不能小于0,请检查",find.getDeviceName());
//        });

        // 必须指定一个中标供应商
        // 报价时，如果相关设备存在报价明细，不允许删除
        Map<String,List<DeviceWorkOffer>> offerByItemId = deviceWorkOfferService.list(Wrappers.<DeviceWorkOffer>query().in("work_id",work.getId()))
                .stream().collect(Collectors.groupingBy(DeviceWorkOffer::getWorkItemId));
        childList.stream().forEach(item -> {
            if (offerByItemId == null || !offerByItemId.containsKey(item.getId())) {
                BusinessException.throwError("设备【%s】尚未进行报价，请先报价",item.getDeviceName());
            }
            long bidNum = offerByItemId.get(item.getId()).stream().filter(tmp -> tmp.getFlagBid()).count();
            BusinessException.throwErrorIf(bidNum == 0,"设备【%s】报价清单没有任何中标供应商，请检查",item.getDeviceName());
            BusinessException.throwErrorIf(bidNum > 1,"设备【%s】报价清单存在多个中标供应商，请检查",item.getDeviceName());

            DeviceWorkOffer offerBid = offerByItemId.get(item.getId()).stream().filter(tmp -> tmp.getFlagBid()).findFirst().get();
            item.setDevicePrice(offerBid.getDevicePrice())
                    .setSupplierId(offerBid.getSupplierId()).setSupplierName(offerBid.getSupplierName())
                    .setMfgId(offerBid.getMfgId()).setMfgName(offerBid.getMfgName());
        });
        deviceWorkItemService.updateBatchById(childList);
    }

    /***
     * @param
     * @Description:  采购合同审核通过后续逻辑
     */
    private void _afterPoContract(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PO_CONTRACT)) {
            return;
        }

        // 更新付款金额
        Double deviceAmount = childList.stream().mapToDouble(DeviceWorkItem::getDeviceAmount).sum();
        List<DeviceContractPayable> payableList = deviceContractPayableService.list(Wrappers.<DeviceContractPayable>query().eq("work_id", work.getId()));
        BusinessException.throwErrorIf(ObjectUtil.length(payableList) == 0, "付款计划为空，无法审核通过");
        if (payableList.stream().mapToDouble(DeviceContractPayable::getPayableRatio).sum() != 100) {
            BusinessException.throwError("付款计划应付款比例合计不为100，请检查");
        }
        Double per = 0d,payableAmount = 0d;
        for(DeviceContractPayable payable : payableList) {
            per = UtilNum.div(payable.getPayableRatio(), 100d, 4);
            payableAmount = UtilNum.mul(per , deviceAmount);
            payable.setPayableAmount(payableAmount);
        }
        deviceContractPayableService.updateBatchById(payableList);

    }

    /***
     * @param
     * @Description:  安装验收审核通过后续逻辑
     */
    private void _afterPoAccept(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PO_ACCEPT)) {
            return;
        }

        childList = childList.stream().filter(item -> item.getDeviceQtyAccept() == null || item.getDeviceQtyAccept() < item.getDeviceQty()).collect(Collectors.toList());
        if (ObjectUtil.length(childList) > 0) {
            BusinessException.throwValidFail("安装验收单【%s】，设备【%s】验收数量少于采购数量，请检查",work.getBusKey(),childList.get(0).getDeviceName());
        }

    }

    /***
     * @param
     * @Description:  采购入库审核通过后续逻辑
     */
    private void _afterPoWi(DeviceWork work, List<DeviceWorkItem> childList) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PO_WI)) {
            return;
        }

        int countSn = childList.stream().mapToInt(DeviceWorkItem::getDeviceQty).sum();
        List<String> workItemIdList = childList.stream().map(DeviceWorkItem::getWorkItemId).distinct().collect(Collectors.toList());
        List<String> snList = serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.DEVICE_SN,countSn);
        List<String> codeList = serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.DEVICE_CODE, workItemIdList.size());
        Map<String,String> codeMap = new HashMap<>();
        int index = 0;
        for(String id : workItemIdList) {
            codeMap.put(id,codeList.get(index));
            index++;
        }
        DeviceLedger deviceLedger;
        List<DeviceLedger> deviceLedgerList = new ArrayList<>();
        index = 0;
        int deviceQty;
        for(DeviceWorkItem workItem : childList) {
            deviceQty = workItem.getDeviceQty();
            while (deviceQty > 0) {
                deviceLedger = new DeviceLedger();
                BeanUtil.copyProperties(workItem,deviceLedger);
                deviceLedger.setId(null);
                deviceLedger.setDeviceCode(codeMap.get(workItem.getWorkItemId())).setDeviceSn(snList.get(index)).setDeviceStatus(DeviceStatus.in_use);
                deviceLedger.setDeptIdOwner(work.getDeptIdFrom()).setDeptNameOwner(work.getDeptNameFrom());
                deviceLedger.setDeptIdUse(work.getDeptIdFrom()).setDeptNameUse(work.getDeptNameFrom());
                index++;
                deviceLedgerList.add(deviceLedger);
                deviceQty--;
            }
        }
        deviceLedgerService.saveBatch(deviceLedgerList);
    }

    /***
     * @param
     * @Description:  盘点后续逻辑
     */
    private void _afterCheck(DeviceWork work, List<DeviceWorkItem> childList, FlowContext flowContext) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_CHECK)) {
            return;
        }

        // 盘点开始
        if (flowContext.getButton().getCode().equals("checkBegin")) {
            QueryWrapper queryWrapper = Wrappers.<DeviceLedger>query();
            switch (work.getCheckType()) {
                case CheckType.all: {

                    break;
                }
                case CheckType.dept: {
                    queryWrapper.eq("dept_id_owner",work.getDeptIdTo());
                    break;
                }
                case CheckType.sp: {
                    queryWrapper.eq("supplier_id",work.getSupplierId());
                    break;
                }
            }
            deviceWorkItemService.remove(Wrappers.<DeviceWorkItem>query().eq("work_id", work.getId()));

            List<DeviceLedger> deviceLedgerList = deviceLedgerService.list(queryWrapper);
            BusinessException.throwErrorIf(ObjectUtil.length(deviceLedgerList) == 0, "没有需要盘点的设备，请删除该盘点单");

            List<DeviceWorkItem> deviceWorkItemList = new ArrayList<>();
            DeviceWorkItem deviceWorkItem;
            for(DeviceLedger item : deviceLedgerList) {
                deviceWorkItem = new DeviceWorkItem();
                BeanUtil.copyProperties(item,deviceWorkItem);
                deviceWorkItem.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
                deviceWorkItem.setCheckResult(CheckResult.no).setWorkId(work.getId());
                deviceWorkItemList.add(deviceWorkItem);
            }
            deviceWorkItemService.saveBatch(deviceWorkItemList);

        }

        if (!flowContext.isEndNode()) {
            return;
        }

        //未盘的标记为缺失
        deviceWorkItemService.update(Wrappers.<DeviceWorkItem>update().set("check_result",CheckResult.loss).eq("work_id", work.getId()).eq("check_result", CheckResult.no));
    }

    /***
     * @param
     * @Description:  折旧后续逻辑
     */
    private void _afterOld(DeviceWork work, List<DeviceWorkItem> childList, FlowContext flowContext) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_OLD)) {
            return;
        }
        // 执行折旧
        if (flowContext.getButton().getCode().equals("execOld")) {
            List<String> ledgerIdList = childList.stream().map(DeviceWorkItem::getLedgerId).collect(Collectors.toList());
            Map<String,DeviceLedger> deviceLedgeById = deviceLedgerService.list(Wrappers.<DeviceLedger>query().in("id", ledgerIdList))
                    .stream().collect(Collectors.toMap(DeviceLedger::getId, item -> item));
            BusinessException.throwErrorIf(ObjectUtil.length(deviceLedgeById.keySet()) != ObjectUtil.length(ledgerIdList), "资产信息缺失，请联系运营人员检查");
            LocalDateTime now = LocalDateTime.now();
            //生成调价单
            DeviceWork deviceWorkChange = new DeviceWork();
            BeanUtil.copyProperties(work,deviceWorkChange);
            deviceWorkChange.setId(IdWorker.getIdStr()).setGmtCreate(now).setGmtModified(now).setModifier(null);
            deviceWorkChange.setFlowModifier(UserUtils.currentUser().getName()).setFlowModified(now).setFlowStatus(GlobalConsts.FLOW_END_VALUE);
            deviceWorkChange.setBusType(DeviceBusMap.DEVICE_PRICE_CHANGE);
            deviceWorkChange.setRemark(StrUtil.format("折旧单: {}",work.getBusKey()));


            List<DeviceWorkItem> childListAdd = new ArrayList<>();
            DeviceWorkItem itemNew;
            Double devicePrice,devicePriceNew,deviceDepreciation;
            List<String> toBeScrappedIdList = new ArrayList<>();
            for(DeviceWorkItem item : childList) {
                if (deviceLedgeById.get(item.getLedgerId()).getDevicePrice() <= 0) {
                    continue;
                }

                itemNew = new DeviceWorkItem();
                BeanUtil.copyProperties(item,itemNew);
                itemNew.setWorkId(deviceWorkChange.getId()).setWorkItemId(item.getId());
                itemNew.setId(null).setGmtCreate(now).setGmtModified(now).setModifier(null);

                devicePrice = deviceLedgeById.get(item.getLedgerId()).getDevicePrice();
                deviceDepreciation = UtilNum.div(deviceLedgeById.get(item.getLedgerId()).getDeviceDepreciation(), 100, 4);
                // 新价格 = 原价格 - 原价格 * 报废率(月报废率/100)
                devicePriceNew = UtilNum.sub(
                        devicePrice,
                        UtilNum.mul(item.getDevicePrice(),deviceDepreciation)
                );
                if (devicePriceNew <=0) {
                    toBeScrappedIdList.add(item.getLedgerId());
                    devicePriceNew = 0d;
                    itemNew.setRemark("价格为0，已进行报废");
                }

                itemNew.setDevicePrice(deviceLedgeById.get(item.getLedgerId()).getDevicePrice());
                itemNew.setDevicePriceNew(devicePriceNew);
                childListAdd.add(itemNew);
            }

            // 调价单
            if (childListAdd.size() > 0) {
                deviceWorkChange.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(DeviceBusMap.getSerialKey(deviceWorkChange.getBusType())));
                this.saveOrUpdate(deviceWorkChange);
                deviceWorkItemService.saveOrUpdateBatch(childListAdd);
                _afterPriceChange(deviceWorkChange, childListAdd, false);

                ledgerIdList = childListAdd.stream().map(DeviceWorkItem::getLedgerId).collect(Collectors.toList());
                deviceLedgerService.unlockBatch(ledgerIdList);
            }

            // 价格小于等于0的进行报废
            if (toBeScrappedIdList.size() > 0) {
                deviceLedgerService.update(Wrappers.<DeviceLedger>update().set("device_status",DeviceStatus.to_be_scrapped).in("id",toBeScrappedIdList));
            }

        }
    }

    /***
     * @param
     * @Description:  维修前置逻辑
     */
    private void _beforeRepair(DeviceWork work,  FlowContext flowContext) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_REPAIR)) {
            return;
        }
        //按钮操作完，维修中
        if (flowContext.getButton().getValueTo().equals("repairing")) {
            List<String> userIdList = StrUtil.split(work.getDispatchUserIds(),",");
            BusinessException.throwErrorIf(!userIdList.contains(UserUtils.currentUser().getId()),"您不在相关派单人中，不可操作");
            work.setDispatchUserIdAccept(UserUtils.currentUser().getId()).setDispatchUserNameAccept(UserUtils.currentUser().getName());
        }

        //按钮操作完，维修完成
        if (flowContext.getButton().getValueTo().equals("repairend")) {
            BusinessException.throwErrorIf(!UserUtils.currentUser().getId().equals(work.getDispatchUserIdAccept()),"您不是当前派单接受人，不可操作");

        }
    }

    /***
     * @param
     * @Description:  调价后续逻辑
     */
    private void _afterPriceChange(DeviceWork work, List<DeviceWorkItem> childList,boolean priceGt0) {
        if (!work.getBusType().equals(DeviceBusMap.DEVICE_PRICE_CHANGE)) {
            return;
        }

        if (priceGt0) {
            childList.stream().filter(item -> item.getDevicePriceNew() == null || item.getDevicePriceNew() <= 0).findFirst().ifPresent(find -> {
                BusinessException.throwError("设备[%s]新单价需要大于0,请检查",find.getDeviceName());
            });
        }

        for(DeviceWorkItem item : childList) {
            deviceLedgerService.update(Wrappers.<DeviceLedger>update().set("device_price",item.getDevicePriceNew()).eq("id",item.getLedgerId()));
        }
    }


    /***
     * @param
     * @Description:  添加报价明细
     */
    private void _addOfferDtlByPo(DeviceWork work) {
        List<DeviceWorkItem> childList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().eq("work_id", work.getPoId()));
        if (ObjectUtil.length(childList) == 0) {
            BusinessException.throwValidFail("采购单【%s】没有采购明细，无法进行报价",work.getPoKey());
        }

        List<String> deviceNameNoPass = childList.stream().filter(tmp -> tmp.getFlagArgumentPass() != GlobalConsts.YES).map(DeviceWorkItem::getDeviceName).collect(Collectors.toList());
        if (ObjectUtil.length(deviceNameNoPass) > 0) {
            BusinessException.throwValidFail("采购单【%s】相关设备【%s】未论证通过，无法进行报价",work.getPoKey(),StringUtils.join(deviceNameNoPass,","));
        }

        for(DeviceWorkItem item : childList) {
            item.setWorkId(work.getId()).setWorkItemId(item.getId());
            item.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        }
        deviceWorkItemService.saveOrUpdateBatch(childList);
    }


    /***
     * @param
     * @Description:  添加合同明细
     */
    private void _addContractDtlByOffer(DeviceWork work) {
        DeviceWork workOffer = this.getOne(Wrappers.<DeviceWork>query().eq("po_id", work.getPoId()).eq("bus_type",DeviceBusMap.DEVICE_PO_OFFER),false);
        BusinessException.throwErrorIf(workOffer == null, "未找到相关报价单，采购单【%s】",work.getPoKey());
        List<DeviceWorkItem> childList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().eq("work_id", workOffer.getId()));
        if (ObjectUtil.length(childList) == 0) {
            BusinessException.throwValidFail("报价单【%s】没有明细，请检查",workOffer.getBusKey());
        }
        childList = childList.stream().filter(item -> item.getSupplierId().equals(work.getSupplierId())).collect(Collectors.toList());
        if (ObjectUtil.length(childList) == 0) {
            BusinessException.throwValidFail("报价单【%s】没有当前签约乙方的中标记录，请检查",workOffer.getBusKey());
        }

        for(DeviceWorkItem item : childList) {
            item.setWorkId(work.getId()).setWorkItemId(item.getId());
            item.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        }
        deviceWorkItemService.saveOrUpdateBatch(childList);
    }


    /***
     * @param
     * @Description:  添加合同明细
     */
    private void _addAcceptDtl(DeviceWork work) {
        DeviceWork workCon = this.getOne(Wrappers.<DeviceWork>query().eq("po_id", work.getPoId()).eq("bus_type",DeviceBusMap.DEVICE_PO_CONTRACT),false);
        BusinessException.throwErrorIf(workCon == null, "未找到相关合同，采购单【%s】",work.getPoKey());
        List<DeviceWorkItem> childList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().eq("work_id", workCon.getId()));
        if (ObjectUtil.length(childList) == 0) {
            BusinessException.throwValidFail("合同【%s】没有明细，请检查",workCon.getBusKey());
        }

        for(DeviceWorkItem item : childList) {
            item.setWorkId(work.getId()).setWorkItemId(item.getId());
            item.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        }
        deviceWorkItemService.saveOrUpdateBatch(childList);
    }


    /***
     * @param
     * @Description:  添加入库明细
     */
    private void _addWiDtl(DeviceWork work) {
        DeviceWork workAccept = this.getOne(Wrappers.<DeviceWork>query().eq("po_id", work.getPoId()).eq("bus_type",DeviceBusMap.DEVICE_PO_ACCEPT),false);
        BusinessException.throwErrorIf(workAccept == null, "未找到相关安装验收单，采购单【%s】",work.getPoKey());
        List<DeviceWorkItem> childList = deviceWorkItemService.list(Wrappers.<DeviceWorkItem>query().eq("work_id", workAccept.getId()));
        if (ObjectUtil.length(childList) == 0) {
            BusinessException.throwValidFail("安装验收单【%s】没有明细，请检查",workAccept.getBusKey());
        }
        List<DeviceWorkItem> childListError = childList.stream().filter(item -> item.getDeviceQtyAccept() == null || item.getDeviceQtyAccept() < item.getDeviceQty()).collect(Collectors.toList());
        if (ObjectUtil.length(childListError) > 0) {
            BusinessException.throwValidFail("安装验收单【%s】，设备【%s】验收数量少于采购数量，请检查",workAccept.getBusKey(),childListError.get(0).getDeviceName());
        }

        for(DeviceWorkItem item : childList) {
            item.setWorkId(work.getId()).setWorkItemId(item.getId());
            item.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
        }
        deviceWorkItemService.saveOrUpdateBatch(childList);
    }
}